<?php

/**
 * @Author: wuchenge
 * @Date:   2022-03-25 15:45:23
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Front\Controllers;

use App\Http\Controllers\ApiController;
use App\Libraries\MarkdownDescribe;
use App\Models\Article;
use App\Models\ArticleLabel;
use App\Models\HotLabel;
use App\Models\Label;
use Illuminate\Http\Request;

class IndexController extends ApiController
{

    public function hots(Request $request)
    {
        $data = HotLabel::orderBy('sort', 'desc')->pluck('name');
        return $this->response($data);
    }

    public function detail(Request $request, int $id)
    {

        $data = Article::find($id)->toArray();
        return $this->response($data);
    }

    public function labels()
    {
        $data = Label::select(['id', 'title', 'img'])
            ->where('status', Label::STATUS_YES)
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();

        return $this->response($data);
    }

    public function lists(Request $request)
    {
        $last_id   = $request->input('last_id', 0); // 分页最后一个id
        $limit     = $request->input('limit', 10); // 分页条数
        $keyword   = $request->input('keyword', ''); // 标题搜索
        $label_ids = $request->input('label_ids', ''); // 标签搜索

        $model = Article::with(['labels'])
            ->where('status', Article::STATUS_YES)
            ->limit($limit)
            ->orderBy('id', 'desc');

        // 标题搜索
        if (!empty($keyword)) {
            $model->where('title', 'like', '%' . $keyword . '%');

            // 插入热搜
            HotLabel::create([
                'name' => $keyword
            ]);
        }

        // 标签搜索
        if (!empty($label_ids)) {
            $label_ids = explode(',', $label_ids);
            $ids       = ArticleLabel::whereIn('label_id', $label_ids)->pluck('article_id');
            $model->whereIn('id', $ids);
        }

        // 分页
        if (!empty($last_id)) {
            $model->where('id', '<', $last_id);
        }

        $count = $model->count();
        $lists = $model->get()->toArray();

        // 简介
        foreach ($lists as $key => $list) {
            $lists[$key]['desc'] = MarkdownDescribe::desc($list['content'], 100);
        }

        $data = [
            'count' => $count,
            'lists' => $lists,
        ];

        return $this->response($data);
    }
}
